package com.fivemin.website_statistics.controller;

import com.fivemin.website_statistics.enums.ResponseEnum;
import com.fivemin.website_statistics.vo.R;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice(basePackageClasses = {com.fivemin.website_statistics.controller.WebUserController.class})
public class WebUserControllerAdvice {
    private static final Logger logger = LogManager.getLogger(WebUserControllerAdvice.class);

    @ExceptionHandler(BindException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e, BindingResult bindingResult){
        logger.error(e.getMessage());
        List<String> errorList = new ArrayList<>();
        if(bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            fieldErrors.forEach(item->{
                errorList.add(item.getField() + item.getDefaultMessage());
            });
        }
        return new R().error(ResponseEnum.PARAMS_BINDING_ERROR,ResponseEnum.PARAMS_BINDING_ERROR.getMsg() + ":" + errorList.toString(),null);
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e){
       e.printStackTrace();
       return new R().error(e.getMessage());
    }
}
